# Re-estimate the models in the main text excluding observations with extreme post-election emotions.
# See Appendix P.




#############
# load data #
#############

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)

load("PSRM Replication Files/PresidentialElectionsPosts.RData")

colnames(president_df)

all(c("populist_present", "polarization") %in% colnames(president_df)) # TRUE

length(unique(president_df$country)) # 26
length(unique(president_df$electionname)) # 29
length(unique(president_df$party_country)) # 52

# focus on 15 days before and after the election
day_range <- 15

sub <- president_df[which(president_df$daysinceelection >= -1*day_range
                          & president_df$daysinceelection <= day_range),]

# winners and losers
winners <- sub[which(sub$win == 1),]
losers <- sub[which(sub$win != 1),]

length(unique(winners$electionname[which(!is.na(winners$polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$economic_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$social_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_present))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_dummy))])) # 27

length(unique(losers$electionname[which(!is.na(losers$polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$economic_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$social_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_present))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_dummy))])) # 27




##################
# winners + love #
##################

winner_love1 <- brm(loveprop ~ post
                    + populist_present + polarization
                    + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                    + Xl + Xr 
                    + (1 + Xl + Xr | party_election),
                    data=winners[which(winners$electionname != "United States_2020"),],
                    warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(winner_love1)[[14]][,5])
#plot(winner_love1)
#summary(winner_love1)

winner_love2 <- brm(loveprop ~ post*populist_present + post*polarization
                    + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                    + Xl + Xr 
                    + (1 + Xl + Xr | party_election),
                    data=winners[which(winners$electionname != "United States_2020"),],
                    warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(winner_love2)[[14]][,5])
#plot(winner_love2)
#summary(winner_love2)




###################
# winners + angry #
###################

winner_angry1 <- brm(angryprop ~ post
                     + populist_present + polarization
                     + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                     + Xl + Xr 
                     + (1 + Xl + Xr | party_election),
                     data=winners[which(!(winners$electionname %in% c("United States_2016", "Slovenia_2017"))),],
                     warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(winner_angry1)[[14]][,5])
#plot(winner_angry1)
#summary(winner_angry1)

winner_angry2 <- brm(angryprop ~ post*populist_present + post*polarization
                     + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                     + Xl + Xr 
                     + (1 + Xl + Xr | party_election),
                     data=winners[which(!(winners$electionname %in% c("United States_2016", "Slovenia_2017"))),],
                     warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(winner_angry2)[[14]][,5])
#plot(winner_angry2)
#summary(winner_angry2)




#################
# losers + love #
#################

loser_love1 <- brm(loveprop ~ post
                   + populist_present + polarization
                   + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                   + Xl + Xr 
                   + (1 + Xl + Xr | party_election),
                   data=losers[which(!(losers$electionname %in% c("Paraguay_2018", "Peru_2016"))),],
                   warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(loser_love1)[[14]][,5])
#plot(loser_love1)
#summary(loser_love1)

loser_love2 <- brm(loveprop ~ post*populist_present + post*polarization
                   + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                   + Xl + Xr 
                   + (1 + Xl + Xr | party_election),
                   data=losers[which(!(losers$electionname %in% c("Paraguay_2018", "Peru_2016"))),],
                   warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(loser_love2)[[14]][,5])
#plot(loser_love2)
#summary(loser_love2)




##################
# losers + angry #
##################

loser_angry1 <- brm(angryprop ~ post
                    + populist_present + polarization
                    + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                    + Xl + Xr 
                    + (1 + Xl + Xr | party_election),
                    data=losers[which(!(losers$electionname %in% c("Taiwan_2020", "Romania_2019", "Georgia_2018"))),],
                    warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(loser_angry1)[[14]][,5])
#plot(loser_angry1)
#summary(loser_angry1)

loser_angry2 <- brm(angryprop ~ post*populist_present + post*polarization
                    + incumbentparty + concurrent + runoff + semipresidential + enc_v1
                    + Xl + Xr 
                    + (1 + Xl + Xr | party_election),
                    data=losers[which(!(losers$electionname %in% c("Taiwan_2020", "Romania_2019", "Georgia_2018"))),],
                    warmup=1000, iter=2000, chains=3, seed=1234)
max(summary(loser_angry2)[[14]][,5])
#plot(loser_angry2)
#summary(loser_angry2)

#save(winner_love1, winner_love2,
#     winner_angry1, winner_angry2,
#     loser_love1, loser_love2,
#     loser_angry1, loser_angry2,
#     file="Stan_Outliers.RData")




##################
# result summary #
##################

load("PSRM Replication Files/Stan_Outliers.RData")

summary(winner_love1)
summary(winner_angry1)
summary(loser_love1)
summary(loser_angry1)

round(posterior_interval(winner_angry1, "post", 0.9), 2)
round(posterior_interval(loser_angry1, "post", 0.9), 2)

round(mean(winner_love1$data[which(winner_love1$data[,2] == 0),1]), 2)
round(mean(winner_angry1$data[which(winner_love1$data[,2] == 0),1]), 2)
round(mean(loser_angry1$data[which(loser_angry1$data[,2] == 0),1]), 2)


# table
f1 <- lm(loveprop ~ post
         + populist_present + polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=winners[which(winners$electionname != "United States_2020"),])

f2 <- lm(loveprop ~ post*populist_present + post*polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=winners[which(winners$electionname != "United States_2020"),])

f3 <- lm(angryprop ~ post
         + populist_present + polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=winners[which(!(winners$electionname %in% c("United States_2016", "Slovenia_2017"))),])

f4 <- lm(angryprop ~ post*populist_present + post*polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=winners[which(!(winners$electionname %in% c("United States_2016", "Slovenia_2017"))),])

f5 <- lm(loveprop ~ post
         + populist_present + polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=losers[which(!(losers$electionname %in% c("Paraguay_2018", "Peru_2016"))),])

f6 <- lm(loveprop ~ post*populist_present + post*polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=losers[which(!(losers$electionname %in% c("Paraguay_2018", "Peru_2016"))),])

f7 <- lm(angryprop ~ post
         + populist_present + polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=losers[which(!(losers$electionname %in% c("Taiwan_2020", "Romania_2019", "Georgia_2018"))),])

f8 <- lm(angryprop ~ post*populist_present + post*polarization
         + incumbentparty + concurrent + runoff + semipresidential + enc_v1
         + Xl + Xr,
         data=losers[which(!(losers$electionname %in% c("Taiwan_2020", "Romania_2019", "Georgia_2018"))),])

# table P.1
stargazer(f1, f3, f5, f7,
          coef=list(fixef(winner_love1)[,1], fixef(winner_angry1)[,1], 
                    fixef(loser_love1)[,1], fixef(loser_angry1)[,1]),
          #se=list(fixef(winner_love1)[,2], fixef(winner_angry1)[,2], 
          #        fixef(loser_love1)[,2], fixef(loser_angry1)[,2]),
          ci.custom=list(fixef(winner_love1)[,3:4], fixef(winner_angry1)[,3:4], 
                         fixef(loser_love1)[,3:4], fixef(loser_angry1)[,3:4]),
          omit="Constant",
          star.cutoffs=NA, 
          digits=2,
          no.space=TRUE,
          dep.var.caption="",
          omit.stat = c("f", "adj.rsq", "rsq", "ser"),
          dep.var.labels=c("Love", "Angry", "Love", "Angry"),
          covariate.labels=c("Post Election",
                             "Populist Involvement", "Polarization",
                             "Incumbent Party", "Concurrent Election",
                             "Runoff", "Semi-Presidential",
                             "Effective Number of Candidates",
                             "Pre-Election Trend (Group Mean)", 
                             "Post-Election Trend (Group Mean)"))

# standard deviation of random effects
getSigmas <- function(model){
  sest <- round(summary(model)[[17]]$party_election[1:3,1], 2)
  ssd <- paste0("[",
                sapply(1:3, function(p){paste(round(summary(model)[[17]]$party_election[p,3:4], 2), 
                                              collapse = ", ")}), "]")
  
  return(c(sest[1], ssd[1], sest[2], ssd[2], sest[3], ssd[3]))
}

sigmas1 <- data.frame(label=c("hatsigmatextIntercept", "",
                              "hatsigmatextPre-Election Trend", "",
                              "hatsigmatextPost-Election Trend", ""),
                      s1=getSigmas(winner_love1),
                      s2=getSigmas(winner_angry1),
                      s3=getSigmas(loser_love1),
                      s4=getSigmas(loser_angry1))
stargazer(t(t(sigmas1)))

c(length(unique(winner_love1$data$party_election)),
  length(unique(winner_angry1$data$party_election)),
  length(unique(loser_love1$data$party_election)),
  length(unique(loser_angry1$data$party_election)))


# table P.2
stargazer(f2, f4, f6, f8,
          coef=list(fixef(winner_love2)[,1], fixef(winner_angry2)[,1], 
                    fixef(loser_love2)[,1], fixef(loser_angry2)[,1]),
          #se=list(fixef(winner_love2)[,2], fixef(winner_angry2)[,2], 
          #        fixef(loser_love2)[,2], fixef(loser_angry2)[,2]),
          ci.custom=list(fixef(winner_love2)[,3:4], fixef(winner_angry2)[,3:4], 
                         fixef(loser_love2)[,3:4], fixef(loser_angry2)[,3:4]),
          omit="Constant",
          star.cutoffs=NA, 
          digits=2,
          no.space=TRUE,
          dep.var.caption="",
          omit.stat = c("f", "adj.rsq", "rsq", "ser"),
          dep.var.labels=c("Love", "Angry", "Love", "Angry"),
          covariate.labels=c("Post Election",
                             "Populist Involvement", "Polarization",
                             "Incumbent Party", "Concurrent Election",
                             "Runoff", "Semi-Presidential",
                             "Effective Number of Candidates",
                             "Pre-Election Trend (Group Mean)", 
                             "Post-Election Trend (Group Mean)",
                             "Post Election times Populist Involvement",
                             "Post Election times Polarization"))

# standard deviation of random effects
sigmas2 <- data.frame(label=c("hatsigmatextIntercept", "",
                              "hatsigmatextPre-Election Trend", "",
                              "hatsigmatextPost-Election Trend", ""),
                      s1=getSigmas(winner_love2),
                      s2=getSigmas(winner_angry2),
                      s3=getSigmas(loser_love2),
                      s4=getSigmas(loser_angry2))
stargazer(t(t(sigmas2)))

c(length(unique(winner_love2$data$party_election)),
  length(unique(winner_angry2$data$party_election)),
  length(unique(loser_love2$data$party_election)),
  length(unique(loser_angry2$data$party_election)))


# plot interaction terms
getStdPostCI <- function(model, var1, var2, intr, label){
  coeftab <- summary(model)[[14]][,c(1,3,4)]
  coeftab <- coeftab[intr,]
  
  temp <- data.frame(label=label,
                     est=coeftab[1],
                     lwr=coeftab[2],
                     upr=coeftab[3])
  colnames(temp) <- c("label", "est", "lwr", "upr")
  return(temp)
}

citab <- rbind(getStdPostCI(winner_love2, 2, 3, 12, "Winner + Love"),
               getStdPostCI(winner_love2, 2, 4, 13, "Winner + Love"),
               getStdPostCI(winner_angry2, 2, 3, 12, "Winner + Angry"),
               getStdPostCI(winner_angry2, 2, 4, 13, "Winner + Angry"),
               getStdPostCI(loser_love2, 2, 3, 12, "Loser + Love"),
               getStdPostCI(loser_love2, 2, 4, 13, "Loser + Love"),
               getStdPostCI(loser_angry2, 2, 3, 12, "Loser + Angry"),
               getStdPostCI(loser_angry2, 2, 4, 13, "Loser + Angry"))

citab$intr <- rep(c("(a) Post Election × Populist Involvement", "(b) Post Election × Polarization"),
                  times=4)

citab$label <- factor(citab$label, levels=rev(unique(citab$label)))
citab$intr <- factor(citab$intr, levels=unique(citab$intr))

# figure P.1
ggplot(data = citab, 
       aes(x = est, y = label)) + 
  facet_wrap(. ~ intr, ncol = 2, scales = "free_x") +
  geom_errorbar(data = citab, aes(xmin = lwr, xmax = upr),
                lwd=0.8, width = 0.1) +
  geom_vline(xintercept=0, lwd=0.5, lty=2) +
  geom_point(cex=4, pch=19) +
  xlab("Posterior Mean and 95% Credible Interval of Interaction Term") +
  ylab("") +
  theme_bw() +
  theme(strip.text.x = element_text(size = 14),
        axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 12),
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16),
        panel.spacing = unit(1, "lines"))

#ggsave("interaction_outlier.pdf", width=12, height=6)
